//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package client_cfg_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/client_cfg_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ExtraMenuDbItem struct {
	MenuId        string `bson:"_id"`
	Name          string `bson:"name"`
	Url           string `bson:"url"`
	TimeStamp     int64  `bson:"timeStamp"`
	Weight        int32  `bson:"weight"`
	MainMenu      bool   `bson:"mainMenu"`
	OpenInBrowser bool   `bson:"openInBrowser"`
}

func (item *ExtraMenuDbItem) ToExtraMenuItem() *client_cfg_api.ExtraMenuItem {
	return &client_cfg_api.ExtraMenuItem{
		Name:          item.Name,
		Url:           item.Url,
		MenuId:        item.MenuId,
		Weight:        item.Weight,
		MainMenu:      item.MainMenu,
		OpenInBrowser: item.OpenInBrowser,
	}
}

type _ExtraMenuDao struct {
	mc *mongo.Collection
}

func newExtraMenuDao(db *mongo.Database) (*_ExtraMenuDao, error) {
	mc := db.Collection(db_ns.DB_NS_CLIENT_CFG + "menu")
	return &_ExtraMenuDao{mc: mc}, nil
}

func (db *_ExtraMenuDao) Insert(ctx context.Context, dbItem *ExtraMenuDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ExtraMenuDao) Exist(ctx context.Context, menuId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": menuId})
	return count > 0, err
}

func (db *_ExtraMenuDao) Update(ctx context.Context, dbItem *ExtraMenuDbItem) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.MenuId}, bson.M{"$set": dbItem})
	return err
}

func (db *_ExtraMenuDao) List(ctx context.Context) ([]*ExtraMenuDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{}, options.Find().SetSort(bson.M{"weight": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*ExtraMenuDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ExtraMenuDao) Remove(ctx context.Context, menuId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": menuId})
	return err
}
